package com.css.dzj.dzjwgr.modules.publicity.service.impl;

import com.css.dzj.dzjwgr.common.util.Constant;
import com.css.dzj.dzjwgr.common.util.R;
import com.css.dzj.dzjwgr.common.util.ServiceUtil;
import com.css.dzj.dzjwgr.modules.publicity.entity.PublicityEntity;
import com.css.dzj.dzjwgr.modules.publicity.entity.QPublicityEntity;
import com.css.dzj.dzjwgr.modules.publicity.mapper.PublicityMapper;
import com.css.dzj.dzjwgr.modules.publicity.service.PublicityService;
import com.css.dzj.dzjwgr.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class PublicityServiceImpl implements PublicityService {

        @Autowired
        private PublicityMapper publicityMapper;

        @Autowired
        private JPAQueryFactory jpaQueryFactory;

        @Autowired
        private ServiceUtil serviceUtil;

        @Autowired
        private HttpServletRequest request;


    /**
     * 新增公示通报信息
     */

    @Override
    @Transactional
    public void add(PublicityEntity publicityEntity) {

        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                publicityEntity.setCreateUser(userInfo.getLoginName());
                publicityEntity.setCreateUserUnit(userInfo.getOrgName());
            }
            //publicityEntity.setId(SnowflakeId.getId());
            publicityEntity.setDelFlag(Constant.NO_DELETE);
            publicityEntity.setCreateTime(new Date());
            publicityEntity.setStatus("1");
            publicityEntity.setOtherMsg("1");//保存发布
            publicityEntity.setReleaseTime(new Date());
            publicityMapper.save(publicityEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 暂存
     * @param publicityEntity
     */
    @Override
    @Transactional
    public void addOnly(PublicityEntity publicityEntity) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                publicityEntity.setCreateUser(userInfo.getLoginName());
                publicityEntity.setCreateUserUnit(userInfo.getOrgName());
            }
            //publicityEntity.setId(SnowflakeId.getId());
            publicityEntity.setDelFlag(Constant.NO_DELETE);
            publicityEntity.setCreateTime(new Date());
            publicityEntity.setStatus("0");
            publicityEntity.setOtherMsg("0");//暂存
            publicityMapper.save(publicityEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /**
     * 修改公示通报信息
     */
    @Override
    @Transactional
    public void update(PublicityEntity publicityEntity) {

    }

    /**
     * 删除公示通报信息
     */
    @Override
    @Transactional
    public Boolean delete(String id) {

        QPublicityEntity qPublicityEntity = QPublicityEntity.publicityEntity;
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("参数为空");
        }
        try {
            jpaQueryFactory
                    .update(qPublicityEntity)
                    .set(qPublicityEntity.delFlag, Constant.DELETE)
                    .where(
                            qPublicityEntity.id.eq(id),
                            qPublicityEntity.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 通过id查询公示通报详情信息
     */

    @Override
    @Transactional
    public PublicityEntity findById (String id){

        if (StringUtils.isEmpty(id)) {

            throw new RuntimeException("参数为空");
        }
        QPublicityEntity qPublicity = QPublicityEntity.publicityEntity;
        return jpaQueryFactory
                .selectFrom(qPublicity)
                .where(qPublicity.id.eq(id),
                        qPublicity.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }


    /**
     * 多条件分页查询公示通报信息
     */
    @Override
    public QueryResults<PublicityEntity> getPublicityList(String createUser, String title, String createUserUnit, String status, String releaseStartTime, String releaseEndTime, Pageable pageable) {

        QPublicityEntity qPublicityEntity = QPublicityEntity.publicityEntity;

        Predicate predicate = qPublicityEntity.isNotNull().or(qPublicityEntity.isNull());
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.createUser.like("%"+createUser.trim()+"%"));
        predicate = ("".equals(title) || title == null) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.title.like("%"+title.trim()+"%"));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.createUserUnit.like("%"+createUserUnit.trim()+"%"));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.status.eq(status));

        if((StringUtils.isEmpty(releaseStartTime))&&(!StringUtils.isEmpty(releaseEndTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qPublicityEntity.releaseTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(releaseStartTime))&&(StringUtils.isEmpty(releaseEndTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate,qPublicityEntity.releaseTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(releaseStartTime))&&(!StringUtils.isEmpty(releaseEndTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
                endDate = sf.parse(releaseEndTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qPublicityEntity.releaseTime.between(startDate,endDate));
        }

        predicate = ExpressionUtils.and(predicate, qPublicityEntity.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qPublicityEntity)
                .where(
                        predicate
                )
                .orderBy(qPublicityEntity.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 多条件分页查询外国人来华公示通报信息
     * @param title
     * @param publicType
     * @return
     */
    public List listPublicity(String title , String publicType,String isPublic) {
        QPublicityEntity qPublicityEntity = QPublicityEntity.publicityEntity;
        Predicate predicate = qPublicityEntity.isNotNull().or(qPublicityEntity.isNull());
        predicate = (title == null || title.isEmpty()) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.title.like("%" + title + "%"));
         if(publicType.equals("0")){
            predicate = ExpressionUtils.and(predicate, qPublicityEntity.publicType.ne("1"));
        }else{
            predicate = ExpressionUtils.and(predicate, qPublicityEntity.publicType.ne("0"));
        }
        predicate = (isPublic == null || isPublic.isEmpty()) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.isPublic.eq(isPublic));
        predicate = ExpressionUtils.and(predicate, qPublicityEntity.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate, qPublicityEntity.status.eq("1")) ;
        List<PublicityEntity> list = jpaQueryFactory.selectFrom(qPublicityEntity)
                .where(predicate)
                .orderBy(qPublicityEntity.releaseTime.desc())
                .fetch();
        return list;
    }

    /**
     * 分页查询所有外国人来华公示通报信息
     * @param  publicType
     * @param  isPublic
     * @return
     */
    @Override
    public List queryAllPublicity(String publicType ,String isPublic) {
        QPublicityEntity qPublicityEntity = QPublicityEntity.publicityEntity;
        Predicate predicate = qPublicityEntity.isNotNull().or(qPublicityEntity.isNull());
        if(publicType.equals("0")){
            predicate = ExpressionUtils.and(predicate, qPublicityEntity.publicType.ne("1"));
        }else{
            predicate = ExpressionUtils.and(predicate, qPublicityEntity.publicType.ne("0"));
        }
        predicate = (isPublic == null || isPublic.isEmpty()) ? predicate : ExpressionUtils.and(predicate, qPublicityEntity.isPublic.eq(isPublic));
        predicate = ExpressionUtils.and(predicate, qPublicityEntity.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate, qPublicityEntity.status.eq("1")) ;
        List<PublicityEntity> list = jpaQueryFactory.selectFrom(qPublicityEntity)
                .where(predicate)
                .orderBy(qPublicityEntity.releaseTime.desc())
                .fetch();
        return list;
    }



}

